<template lang='pug'>
  section
    van-nav-bar(
      left-arrow
      title="确认订单"
      @click-left="$router.back()"
      )
    //- vancontact
    vanaddress(
      :list="addressList" 
      @add="addAddress" 
      v-model="addressIndex" 
      :isLoading="vanaddressLoading"
      :addressInfo="addressInfo"
      @edit="vanaddressEdit"
      @delete="deleteAddress"
      )
    van-card(
      :num="order.quantity"
      :price="order.currentUnitPrice"
      :title="order.productName"
      :desc="order.title"  
      :thumb="order.productImage"
      v-for="order in orders"
      :key="order.id"
      )
      div(slot="footer"): van-stepper(v-model="order.quantity" :integer="true")
    van-cell-group
      //- van-cell(title="购买数量")
      //-   van-stepper(v-model="quantity" :integer="true")
      van-cell(title="配送方式" is-link value="快递 免邮")
      van-cell(title="积分" is-link :value="points" @click="choosePoints")
      van-field(
        v-model="order.remark"
        label="留言"
        type="textarea"
        placeholder="选填：填写内容和卖家协商确认"
        rows="1"
        autosize
        )
    van-submit-bar(
      :loading="isLoading"
      :price="total * 100"
      button-text="提交订单"
      :disabled="!canSubmit"
      @submit="buy"
      )
    van-popup(
      v-model="choosePointsShow"
      position="bottom"
      )
      .choose-point
        
        //- van-field(v-model="order.points" placeholder="请填写要使用的积分" label-align="center" input-align="center" is-link)
        van-field(:value="`使用全部：${points}积分`" input-align="center" :readonly="true" is-link @click="order.points = points")
        van-field(value="不使用积分" input-align="center" :readonly="true" is-link)
        van-cell(title="要使用的积分：")
          van-stepper(
            v-model="order.points"
            integer
            :min="0"
            :max="points"
            :step="10"
            )
        van-field.choose-point-cancel.border-t-1px(
          value="取消" 
          input-align="center" 
          :readonly="true" 
          :border="false" 
          :error="true"
          @click="choosePointsShow = false"
          )
        
    //- van-stepper(v-model="value")

</template>

<script type='text/ecmascript-6'>
  import vancontact from '~/components/vancontact'
  import vanaddress from '~/components/vanaddress'
  import { getorder } from '~/assets/js/order'
  import pay from '~/assets/js/pay'

  export default {
    components: {
      vancontact,
      vanaddress
    },
    async asyncData({ route }) {
      const fromCart = route.query.fromCart

      return {fromCart}
      // const id = ctx.route.query.id
      // const resp = await ctx.$post('/api/platform/product/findProduct', {id})
      // return { commodity: resp.data, id }
    },
    data() {
      return {
        choosePointsShow: false,
        isLoading: false,
        vanaddressLoading: false,
        quantity: this.$route.query.quantity,
        order: {
          userId: '',
          receiverName: '',
          receiverPhone: null,
          receiverAddress: '',
          payment: 0, // 实际付款金额 元,保留两位小数
          points: null, // 实际付款积分
          postage: 0, // 配送费
          remark: '', // 留言
          orderDetails: [
            {
              productId: '', // 商品id
              productName: '', // 商品名 
              currentUnitPrice: '', // 生成订单时的商品单价，单位是元,保留两位小数
              userId: '',
              quantity: 0, // 商品数量
              totalPrice: 0, // 商品总价
            }
          ]
        },
        address: null,
        addresss: [],
        addressIndex: -1,
        orders: [],
        addressInfo: {},
      };
    },
    watch: {
      addresss: {
        handler(arr) {
          this.addressIndex = (arr || []).findIndex(item => item.defaultAddress === 1)
        },
        immediate: true
      },
      addressIndex: {
        handler(index) {
          const address = this.addressList[index] || {}
          const { name: receiverName, tel: receiverPhone, address: receiverAddress } = address

          // this.order.receiverName = receiverName
          // this.order.receiverPhone = receiverPhone
          // this.order.receiverAddress = receiverAddress

          this.$set(this.order, 'receiverName', receiverName)
          this.$set(this.order, 'receiverPhone', receiverPhone)
          this.$set(this.order, 'receiverAddress', receiverAddress)
        },
        immediate: true
      },
      total: {
        handler(amount) {
          this.order.payment = amount
        },
        immediate: true
      },
    },
    computed: {
      total() {
        if (!this.orders || !this.orders.length) return 0
        return this.orders.reduce((total, currentItem) => total + currentItem.currentUnitPrice * currentItem.quantity, 0)
      },
      user() { return this.$store.state.authUser || {} },
      userId() {
        if (!this.user ||!this.user.user) return ''
        return this.user.user.id
      },
      points() {
        if (!this.user ||!this.user.user) return 0
        return this.user.user.points
      },
      openId() {
        if (!this.user ||!this.user.userWx) return ''
        return this.user.userWx.openid
      },
      addressList() {
        return this.addresss.map(address => {
          const { id, receiverName: name, receiverMobileNo: tel, provinceName, cityName, districtName, detailAddress } = address

          return {
            id,
            name,
            tel,
            address: provinceName + cityName + districtName + detailAddress
          }
        })
          //   {
        //     id: '1',
        //     name: '张三',
        //     tel: '13000000000',
        //     address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室'
        //   },
      },
      canSubmit() {
        const {receiverName, receiverPhone, receiverAddress} = this.order
        return !!receiverName && !!receiverPhone && !!receiverAddress
      }
    },
    beforeMount() {
      this.getAddress()
      this.orders = getorder()
      console.log('orders', this.orders)
    },
    methods: {
      choosePoints() {
        if (!this.points) {
          this.$toast('您还没有积分可用')
          return
        }
        this.choosePointsShow = true
      },
      vanaddressEdit(index) {
        const address = this.addresss[index]

        if (!address) {
          this.addressInfo = {}
          return
        }
        const { 
          id,
          receiverName: name, 
          receiverMobileNo: tel, 
          provinceName: province, 
          cityName: city, 
          districtName: county, 
          detailAddress: addressDetail,
          districtId: areaCode,
          receiverZipCode: postalCode,
          defaultAddress: isDefault,
          } = address
          this.addressInfo = {
            id,
            name,
            tel,
            province,
            city,
            county,
            addressDetail,
            areaCode,
            postalCode,
            isDefault: isDefault === 1
          }
      },
      async addAddress(content) {
        console.log('content', content)
        const { 
          name: receiverName, 
          tel: receiverMobileNo, 
          province: provinceName,
          city: cityName,
          county: districtName,
          areaCode: districtId,
          addressDetail: detailAddress, 
          postalCode: receiverZipCode,
          isDefault,
        } = content
        const data = {
          userId: this.userId,
          receiverName,
          receiverMobileNo,
          provinceName,
          cityName,
          districtName,
          districtId,
          detailAddress,
          receiverZipCode,
          defaultAddress: isDefault ? 1 : 0, // 0 非默认 1 默认
        }
        this.vanaddressLoading = true
        const resp = await this.$post('/api/platform/shipping/add', data)
        this.vanaddressLoading = false
        if (resp.msg === 'ok') {
          this.$toast('新增收货地址成功')
          this.getAddress()
        } else {
          this.$toast('新增收货地址失败')
        }
      },
      deleteAddress(id) {
        console.log('id', id)
        this.$post('/api/platform/shipping/delete', { id, userId: this.userId }).then(resp => {
          if (resp.msg === 'ok') {
            this.$toast.success('删除成功')

            const index = this.addresss.findIndex(item => item.id === id)
            this.addresss.splice(index, 1)
          } else {
            this.$toast.fail('删除失败')
          }
        })
      },
      async getAddress() {
        const resp = await this.$post('/api/platform/shipping/shippingPage', {userId: this.userId})
        this.addresss = resp.data || []
      },
      buy() {
        this.order.userId = this.userId
        this.orders.forEach(order => {
          order.totalPrice = order.currentUnitPrice * order.quantity
        })

        this.order.orderDetails = this.orders
        console.log(this.order)
        this.isLoading = true

        const api = fromCart ? 'addOrderByCart' : 'add'
        this.$post(`/api/platform/order/${api}`, this.order, 'JSON')
          .then(resp => {
            const order = resp.data
            const { payment, orderNo } = order || {}
            // this.$toast.success('订单提交成功')
            pay(payment, orderNo, this.userId, this.openId)
              .finally(() => {
                this.$router.replace('/order')
              })
          })
          .catch(err => {
            this.$toast.fail('提交订单失败')
          })
          .finally(() => { this.isLoading = false })
        // this.$router.


      }
    }
  };
</script>

<style lang='stylus' rel='stylesheet/stylus' scoped>

@import '~assets/stylus/variable.styl'
@import '~assets/stylus/mixin.styl'
 
.choose-point
  position relative
  padding-top 1rem
  .van-field
    line-height 2.5
  &-cancel
    margin-top 100px
    text-align center
    border-t-1px($color-border)
</style>
